package com.sztu.shirocore;

import com.sztu.pojo.User;
import com.sztu.service.UserService;
import com.sztu.token.JwtToken;
import com.sztu.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken token= (JwtToken) authenticationToken;
        String jwtToken=token.getToken();
        Claims claims= (Claims) JwtUtil.parseToken(jwtToken);
        User user=userService.queryUserByName((String) claims.getId());
        if(user==null) {
            return null;
        }
        return new SimpleAuthenticationInfo(user.getName(),user.getPwd(),getName());
    }
}
